// pages/magnetic-detect/magnetic-detect.js
const app = getApp()

Page({
  data: {
    // 磁场数据
    currentMagnetic: 0,
    baselineMagnetic: 0,
    magneticChange: 0,
    compassDirection: 0,
    
    // 检测状态
    isDetecting: false,
    baselineSet: false,
    
    // 图表数据
    chartData: [],
    maxDataPoints: 50,
    
    // 异常检测
    anomalies: [],
    normalThreshold: 10,
    warningThreshold: 25,
    dangerThreshold: 50,
    
    // 变化等级
    changeLevel: 'normal',
    
    // 设置
    showSettings: false,
    showGuide: false,
    sensitivity: 5,
    sampleInterval: 500,
    vibrationEnabled: true,
    soundEnabled: false,
    
    // 检测计时器
    detectionTimer: null,
    detectionStartTime: null
  },

  onLoad() {
    console.log('磁场感应检测页面加载')
    this.initChart()
    this.loadSettings()
    
    // 显示操作提示
    setTimeout(() => {
      wx.showModal({
        title: '磁场检测说明',
        content: '1. 先点击"设置基准"按钮设置基准值\n2. 基准设置完成后，点击"开始检测"按钮\n3. 移动手机观察磁场变化',
        showCancel: false,
        confirmText: '我知道了'
      })
    }, 1000)
  },

  onShow() {
    // 保持屏幕常亮
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
  },

  onHide() {
    this.stopDetection()
  },

  onUnload() {
    this.cleanup()
  },

  // 清理资源
  cleanup() {
    this.stopDetection()
    wx.setKeepScreenOn({
      keepScreenOn: false
    })
    wx.stopCompass()
  },

  // 加载设置
  loadSettings() {
    const settings = app.utils.getUserSettings()
    this.setData({
      sensitivity: settings.magneticSensitivity || 5,
      sampleInterval: settings.magneticSampleInterval || 500,
      vibrationEnabled: settings.vibrationEnabled !== false,
      soundEnabled: settings.soundEnabled || false
    })
    
    // 更新阈值
    this.updateThresholds()
  },

  // 更新检测阈值
  updateThresholds() {
    const baseSensitivity = this.data.sensitivity
    this.setData({
      normalThreshold: baseSensitivity * 2,
      warningThreshold: baseSensitivity * 5,
      dangerThreshold: baseSensitivity * 10
    })
  },

  // 初始化图表
  initChart() {
    const ctx = wx.createCanvasContext('magneticChart', this)
    this.chartContext = ctx
    this.drawChart()
  },

  // 绘制图表
  drawChart() {
    const ctx = this.chartContext
    if (!ctx) return
    
    const canvasWidth = 300
    const canvasHeight = 150
    const padding = 20
    const chartWidth = canvasWidth - 2 * padding
    const chartHeight = canvasHeight - 2 * padding
    
    // 清空画布
    ctx.clearRect(0, 0, canvasWidth, canvasHeight)
    
    // 绘制背景
    ctx.setFillStyle('#f8f9fa')
    ctx.fillRect(0, 0, canvasWidth, canvasHeight)
    
    // 绘制边框
    ctx.setStrokeStyle('#dee2e6')
    ctx.setLineWidth(1)
    ctx.strokeRect(padding, padding, chartWidth, chartHeight)
    
    // 绘制基准线
    if (this.data.baselineSet) {
      const baselineY = padding + chartHeight / 2
      ctx.setStrokeStyle('#6c757d')
      ctx.setLineDash([5, 5])
      ctx.beginPath()
      ctx.moveTo(padding, baselineY)
      ctx.lineTo(padding + chartWidth, baselineY)
      ctx.stroke()
      ctx.setLineDash([])
    }
    
    // 绘制数据线
    if (this.data.chartData.length > 1) {
      const data = this.data.chartData
      const maxValue = Math.max(...data.map(d => Math.abs(d.change)))
      const scale = maxValue > 0 ? chartHeight / 2 / maxValue : 1
      
      ctx.setStrokeStyle('#007bff')
      ctx.setLineWidth(2)
      ctx.beginPath()
      
      data.forEach((point, index) => {
        const x = padding + (index / (data.length - 1)) * chartWidth
        const y = padding + chartHeight / 2 - point.change * scale
        
        if (index === 0) {
          ctx.moveTo(x, y)
        } else {
          ctx.lineTo(x, y)
        }
      })
      
      ctx.stroke()
      
      // 绘制异常点
      data.forEach((point, index) => {
        if (Math.abs(point.change) > this.data.warningThreshold) {
          const x = padding + (index / (data.length - 1)) * chartWidth
          const y = padding + chartHeight / 2 - point.change * scale
          
          ctx.setFillStyle(Math.abs(point.change) > this.data.dangerThreshold ? '#dc3545' : '#ffc107')
          ctx.beginPath()
          ctx.arc(x, y, 3, 0, 2 * Math.PI)
          ctx.fill()
        }
      })
    }
    
    ctx.draw()
  },

  // 设置基准值
  setBaseline() {
    if (this.data.isDetecting) {
      wx.showToast({
        title: '请先停止检测',
        icon: 'error'
      })
      return
    }

    wx.showModal({
      title: '设置基准值',
      content: '请将手机放在空旷区域（远离电子设备），点击确定开始设置基准磁场值。',
      success: (res) => {
        if (res.confirm) {
          this.performBaselineSetup()
        }
      }
    })
  },

  // 执行基准值设置
  performBaselineSetup() {
    // 开始磁力计监听来获取基准值
    wx.startCompass({
      success: () => {
        wx.showLoading({
          title: '正在获取基准值...'
        })
        
        let samples = []
        const sampleCount = 10
        
        const onCompassChange = (res) => {
          // 使用真实的磁力计数据
          // 注意：微信小程序的compass API主要提供方向信息，不是真正的磁场强度
          // 这里使用direction和accuracy作为磁场强度的近似值
          const magnetic = Math.abs(res.direction || 0) + Math.abs(res.accuracy || 0)
          samples.push(magnetic)
          
          if (samples.length >= sampleCount) {
            wx.offCompassChange(onCompassChange)
            wx.hideLoading()
            
            // 计算平均值作为基准
            const baseline = samples.reduce((sum, val) => sum + val, 0) / samples.length
            
            this.setData({
              baselineMagnetic: baseline,
              baselineSet: true,
              chartData: []
            })
            
            wx.showToast({
              title: '基准值设置完成',
              icon: 'success'
            })
            
            this.drawChart()
          }
        }
        
        wx.onCompassChange(onCompassChange)
        
        // 10秒超时
        setTimeout(() => {
          if (samples.length < sampleCount) {
            wx.offCompassChange(onCompassChange)
            wx.hideLoading()
            wx.showToast({
              title: '获取基准值超时',
              icon: 'error'
            })
          }
        }, 10000)
      },
      fail: (err) => {
        console.error('启动磁力计失败:', err)
        wx.showModal({
          title: '磁力计启动失败',
          content: '请检查设备是否支持磁力计功能',
          showCancel: false
        })
      }
    })
  },

  // 开始检测
  startDetection() {
    if (!this.data.baselineSet) {
      wx.showModal({
        title: '设置基准值',
        content: '检测前需要先设置基准磁场值。请在空旷区域（远离电子设备）点击"设置基准"按钮。',
        showCancel: false,
        confirmText: '我知道了'
      })
      return
    }

    this.setData({
      isDetecting: true,
      detectionStartTime: Date.now(),
      anomalies: []
    })

    // 开始磁力计监听
    wx.startCompass({
      success: () => {
        this.startMagneticMonitoring()
        wx.showToast({
          title: '开始磁场检测',
          icon: 'success'
        })
      },
      fail: (err) => {
        console.error('启动磁力计失败:', err)
        this.setData({ isDetecting: false })
        wx.showToast({
          title: '磁力计启动失败',
          icon: 'error'
        })
      }
    })
  },

  // 开始磁场监控
  startMagneticMonitoring() {
    const onCompassChange = (res) => {
      if (!this.data.isDetecting) return

      // 使用真实的磁力计数据
      const magnetic = Math.abs(res.direction || 0) + Math.abs(res.accuracy || 0)
      
      const change = magnetic - this.data.baselineMagnetic
      const changeLevel = this.getChangeLevel(Math.abs(change))
      
      // 更新数据
      this.setData({
        currentMagnetic: magnetic,
        magneticChange: change,
        changeLevel: changeLevel,
        compassDirection: res.direction || 0
      })
      
      // 添加到图表数据
      const chartData = [...this.data.chartData]
      chartData.push({
        timestamp: Date.now(),
        value: magnetic,
        change: change
      })
      
      // 限制数据点数量
      if (chartData.length > this.data.maxDataPoints) {
        chartData.shift()
      }
      
      this.setData({ chartData })
      
      // 检测异常
      this.checkAnomaly(magnetic, change)
      
      // 更新图表
      this.drawChart()
    }

    wx.onCompassChange(onCompassChange)
    
    // 定期检测（补充机制）
    this.data.detectionTimer = setInterval(() => {
      if (!this.data.isDetecting) return
      
      // 这里可以添加额外的检测逻辑
    }, this.data.sampleInterval)
  },

  // 获取变化等级
  getChangeLevel(absChange) {
    if (absChange <= this.data.normalThreshold) return 'normal'
    if (absChange <= this.data.warningThreshold) return 'warning'
    return 'danger'
  },

  // 检测异常
  checkAnomaly(magnetic, change) {
    const absChange = Math.abs(change)
    
    if (absChange > this.data.warningThreshold) {
      const level = absChange > this.data.dangerThreshold ? 'danger' : 'warning'
      const levelText = level === 'danger' ? '高异常' : '中异常'
      
      const anomaly = {
        timestamp: Date.now(),
        value: magnetic,
        change: change,
        level: level,
        levelText: levelText,
        formatTime: new Date().toLocaleTimeString()
      }
      
      const anomalies = [...this.data.anomalies]
      anomalies.push(anomaly)
      
      this.setData({ anomalies })
      
      // 提醒用户
      if (this.data.vibrationEnabled) {
        wx.vibrateShort()
      }
      
      if (this.data.soundEnabled) {
        // 这里可以播放提示音
      }
      
      console.log('检测到磁场异常:', anomaly)
    }
  },

  // 停止检测
  stopDetection() {
    this.setData({
      isDetecting: false
    })
    
    wx.offCompassChange()
    wx.stopCompass()
    
    if (this.data.detectionTimer) {
      clearInterval(this.data.detectionTimer)
      this.data.detectionTimer = null
    }
    
    wx.showToast({
      title: '检测已停止',
      icon: 'none'
    })
  },

  // 清除数据
  clearData() {
    wx.showModal({
      title: '确认清除',
      content: '是否清除所有检测数据？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            chartData: [],
            anomalies: [],
            currentMagnetic: 0,
            magneticChange: 0,
            changeLevel: 'normal'
          })
          
          this.drawChart()
          
          wx.showToast({
            title: '数据已清除',
            icon: 'success'
          })
        }
      }
    })
  },

  // 保存结果
  saveResult() {
    if (!this.data.detectionStartTime) {
      wx.showToast({
        title: '请先开始检测',
        icon: 'error'
      })
      return
    }

    const result = {
      id: app.utils.generateId(),
      timestamp: Date.now(),
      location: '',
      detectType: 'magnetic',
      result: {
        magnetic: {
          baseline: this.data.baselineMagnetic,
          anomalies: this.data.anomalies,
          totalDataPoints: this.data.chartData.length,
          detectionDuration: Date.now() - this.data.detectionStartTime
        }
      },
      riskLevel: app.utils.assessRiskLevel({
        magnetic: { anomalies: this.data.anomalies }
      }),
      notes: ''
    }

    // 保存到本地存储
    const history = wx.getStorageSync('detection_history') || []
    history.unshift(result)
    wx.setStorageSync('detection_history', history)

    wx.showModal({
      title: '保存成功',
      content: `检测结果已保存\n异常点: ${this.data.anomalies.length} 个\n风险等级: ${result.riskLevel}`,
      showCancel: false,
      success: () => {
        wx.showModal({
          title: '查看历史',
          content: '是否跳转到历史记录页面？',
          success: (res) => {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/history/history'
              })
            }
          }
        })
      }
    })
  },

  // 切换设置面板
  toggleSettings() {
    this.setData({
      showSettings: !this.data.showSettings
    })
  },

  // 切换指南面板
  toggleGuide() {
    this.setData({
      showGuide: !this.data.showGuide
    })
  },

  // 灵敏度改变
  onSensitivityChange(e) {
    const sensitivity = parseInt(e.detail.value)
    this.setData({ sensitivity })
    this.updateThresholds()
  },

  // 采样间隔改变
  onSampleIntervalChange(e) {
    const interval = parseInt(e.detail.value)
    this.setData({ sampleInterval: interval })
  },

  // 震动提醒切换
  onVibrationToggle(e) {
    this.setData({
      vibrationEnabled: e.detail.value
    })
  },

  // 声音提醒切换
  onSoundToggle(e) {
    this.setData({
      soundEnabled: e.detail.value
    })
  },

  // 分享给好友
  onShareAppMessage() {
    const anomalyCount = this.data.anomalies.length
    const isDetecting = this.data.isDetecting
    
    return {
      title: anomalyCount > 0 ? 
        `磁场检测发现 ${anomalyCount} 个异常点 - 安心住助手` : 
        isDetecting ? '正在进行磁场检测 - 安心住助手' : '磁场感应检测工具 - 安心住助手',
      desc: '使用手机磁力计检测电子设备的磁场异常',
      path: '/pages/magnetic-detect/magnetic-detect'
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '磁场感应检测 - 安心住助手',
      query: 'tool=magnetic'
    }
  }
})
